package com.example.appforegrounddemo

import android.annotation.SuppressLint
import android.app.ActivityManager
import android.os.Bundle
import android.util.Log
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {
    private lateinit var resultTextView: TextView
    private lateinit var checkButton: TextView
    private val TAG = "MainTest"

    @SuppressLint("MissingInflatedId")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        resultTextView = findViewById(R.id.textView)
        checkButton = findViewById(R.id.checkButton)
        resultTextView.setOnClickListener {
            val foregroundApp = getForegroundApp()
            checkButton.text = buildString {
                append("前台应用: ")
                append(foregroundApp)
            }
            Log.d(TAG, "===前台应用===: $foregroundApp")
            Toast.makeText(this@MainActivity, "前台应用信息为: $foregroundApp", Toast.LENGTH_SHORT).show()
        }
    }

    /**
     * 获取前台app信息
     */
    private fun getForegroundApp(): String {
        val am = getSystemService(ACTIVITY_SERVICE) as ActivityManager
        val tasks = am.getRunningTasks(1)
        if (tasks.isNotEmpty()) {
            val taskInfo = tasks[0]
            return """
            ${taskInfo.topActivity?.packageName}
            ${taskInfo.topActivity?.className}
            """.trimIndent()
        }
        return "无法获取前台应用"
    }
}